import { createSlice } from '@reduxjs/toolkit'

function reduceFormState() {
  return {
    num1: null,
    num2: null,
    total: 0,
  }
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState: reduceFormState(),
  reducers: {
    setReduceFormFun: (state, { payload: { key, value } }) => {
      state[key] = value
    },
    setReduceFormState: () => {
      return reduceFormState()
    },

    reduceTotal: (state, { payload: { type } }) => {
      const num1 = Number(state.num1)
      const num2 = Number(state.num2)
      let total = 0

      switch (type) {
        case '+':
          total = num1 + num2
          break
        case '-':
          total = num1 - num2
          break

        case '*':
          total = num1 * num2
          break

        case '/':
          total = num1 / num2
          break
      }
      state.total = total
    },
  },
})

// 为每个 case reducer 函数生成 Action creators
export const { setReduceFormFun, setReduceFormState, reduceTotal } = counterSlice.actions

export default counterSlice.reducer
